<?php

namespace app\manystore\controller\salescenter;

use app\common\controller\ManystoreBase;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

use think\Db;
use app\manystore\Model\UserModel;
use app\manystore\Model\UserInfo;
use app\manystore\Model\CampusClewConsultantModel;
use app\manystore\Model\ManystoreModel;
use app\manystore\Model\CampusStudentSourceModel;
use app\manystore\Model\CampusClewlabelModel;
use app\manystore\Model\CourseModel;
use app\manystore\Model\CampusFollowModel;
use app\manystore\Model\TypeModel;
use app\manystore\Model\GrowthPortfolioModel;
use app\manystore\Model\CampusClassStudent;
use app\manystore\Model\CampusClassDateRecord;
use app\manystore\Model\CampusCourseOrderSublevel;
/**
 * 跟进接口
 */
class FollowUp extends ManystoreBase
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth = [];

    public function _initialize()
    {
        parent::_initialize();
    }

    private function AuthParams($auth = [])
    {
        $param_tmp = $this->request->param();
        $param = [];
        foreach ($auth as $key => $value)
        {
            if(isset($param_tmp[$value]) && $param_tmp[$value] != '')
            {
                $param[$value] = $param_tmp[$value];
            }
        }

        return $param;
    }

    /**
     * 获取跟进记录列表
     *
     * @ApiTitle    获取跟进中信息列表

     * @ApiParams (name="status", type="integer", required=false, description="跟进计划或记录:0=全部,1=未开始,2=已取消,3=已逾期,4=已完成,5=今日待跟进,6=以后待跟进")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657959411",
          "data": [
            {
              "id": "1",//记录ID
              "truename": "张小福",//线索名称
              "label": ["有潜力"],//标签
              "createtime": "2022-06-15 20:59:41",//跟进记录创建时间
              "follow_user": "思明校区",//跟进人
              "content": "惺惺惜惺惺想寻寻寻寻寻寻寻寻寻寻寻寻寻寻寻寻",//跟进内容
              "task_status": 0,//任务状态:0=未开始,1=已取消,2=已逾期,3=已完成
              "images": "",//图片
              "follow_stage": "承诺到访",//跟进阶段
              "plan_time": "1970-01-01 08:00:00",//计划跟进时间
              "follow_way": "电话",//跟进方式
              "cancel_why": null,//取消原因
              "course_consultant": "小天",//顾问姓名
              "nextfollow_time": "2022-06-15 20:27:00",//下次跟进时间
              "lastfollow_time": "1970-01-01 08:00:00",//最后一次跟进时间
              "complete_time": "1970-01-01 08:00:00"//完成时间
            },
            ......
          ]
        })
     */
    public function getFollowingRecordList()
    {
        $status = intval($this->request->param('status'));

        //标签
        $label_list_tmp = TypeModel::field('id,name')->where('type','labelmanage')->select();
        $label_list = [];
        foreach ($label_list_tmp as $key => $value)
        {
            $label_list[$value['id']] = $value['name'];
        }

        $follow_record = CampusFollowModel::field('a.id,u.truename,u.label,a.createtime,m.username as follow_user,a.content,a.task_status,a.images,t1.name as follow_stage,t2.name as follow_way,a.plan_time,a.cancel_why,c.truename as course_consultant,a.nextfollow_time,a.lastfollow_time,a.complete_time')
        ->alias('a')
        ->join('ss_manystore m','a.follow_uid = m.id','left')
        ->join('ss_type t1','t1.id = a.follow_stage','left')
        ->join('ss_type t2','t2.id = a.follow_way','left')
        ->join('ss_user u','u.id = a.clew_id','left')
        ->join('ss_campus_clew_consultant c','u.course_consultant = c.id','left')
        ->where(['a.follow_uid' => $this->auth->id])
        ->where(function($query) use ($status){
            $where = [];

            if($status == 1)
            {
                //未开始【时间未到，且为未开始状态】
                $where['a.task_status'] = 0;
                $where['a.plan_time'] = ['>',time()];
                $query->where($where);
            }
            else if($status == 2)
            {
                //已取消状态
                $where['a.task_status'] = 1;
                $query->where($where);
            }
            else if($status == 3)
            {
                //逾期【时间已到但未操作或状态为逾期】
                $where['a.task_status'] = 0;
                $where['a.plan_time'] = ['<',time()];
                $query->where($where)->whereOr('a.task_status',2);
            }
            else if($status == 4)
            {
                //已取消状态
                $where['a.task_status'] = 3;
                $query->where($where);
            }
            else if($status == 5)
            {
                //今日待跟进
                $where['a.task_status'] = 0;
                $where['a.plan_time'] = ['>=',strtotime(date('Y-m-d 00:00:00'))];
                $where['a.plan_time'] = ['<=',strtotime(date('Y-m-d 23:59:59'))];
                $query->where($where);
            }
            else if($status == 6)
            {
                //以后待跟进
                $where['a.task_status'] = 0;
                $where['a.plan_time'] = ['>',strtotime(date('Y-m-d 23:59:59'))];
                $query->where($where);
            }
        })
        ->select();


        foreach ($follow_record as & $value)
        {
            if(!empty($value['label']))
            {
                $user_label = explode(',', $value['label']);
                $user_label_arr = [];
                foreach ($user_label as $v) {
                    if(!empty($label_list[$v]))
                    {
                        $user_label_arr[] = $label_list[$v];
                    }
                }

                $value['label'] = $user_label_arr;
            }
            else
            {
                $value['label'] = [];
            }
            
            $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
            if($value['task_status'] == 0 && $value['plan_time'] > time())
            {
                $value['task_status'] = 2;
            }
            $value['plan_time'] = date('Y-m-d H:i:s',$value['plan_time']);

            $value['nextfollow_time'] = date('Y-m-d H:i:s',$value['nextfollow_time']);
            $value['lastfollow_time'] = date('Y-m-d H:i:s',$value['lastfollow_time']);
            $value['complete_time'] = date('Y-m-d H:i:s',$value['complete_time']);
        }
        $this->success('获取数据成功','',$follow_record);
    }

    /**
     * 获取跟进记录详情
     *
     * @ApiTitle    获取跟进中信息列表

     * @ApiParams (name="type", type="integer", required=false, description="根据学员或记录查询【0=学员,1=记录】")
     * @ApiParams (name="id", type="integer", required=false, description="学员ID或记录ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657959411",
          "data": [
            {
              "id": "1",//记录ID
              "createtime": "2022-06-15 20:59:41",//跟进记录创建时间
              "follow_user": "思明校区",//跟进人
              "content": "惺惺惜惺惺想寻寻寻寻寻寻寻寻寻寻寻寻寻寻寻寻",//跟进内容
              "task_status": 0,//任务状态:0=未开始,1=已取消,2=已逾期,3=已完成
              "images": "",//图片
              "follow_stage": "承诺到访",//跟进阶段
              "follow_way": "电话",//跟进方式
              "cancel_why": null//取消原因
            },
            ......
          ]
        })
     */
    public function getFollowingRecordInfo()
    {
        $type = intval($this->request->param('type'));
        $id = intval($this->request->param('id'));

        // $info = UserModel::field('a.id,a.truename,a.label,a.age_year,a.age_month,a.follow_status,a.intention_level,a.avatar,a.gender,a.follow_uid,c.truename as course_consultant')
        // ->alias('a')
        // ->where(['a.id' => $id])
        // ->join('ss_campus_clew_consultant c','a.course_consultant = c.id','left')
        // ->find();

        // if(empty($info))
        // {
        //     $this->error('线索不存在');
        // }

        // if($info['follow_uid'] != $this->auth->id && ($this->auth->level == 1 && $info['shop_id'] != $this->auth->shop_id))
        // {
        //     $this->error('你不是该线索的跟进人或校区负责人,无权查看');
        // }

        if($type == 0)
        {
            $where = ['a.clew_id' => $id];
        }
        else
        {
            $where = ['a.id' => $id];
        }

        $follow_record = CampusFollowModel::field('a.id,a.createtime,c.truename as course_consultant,m.username as follow_user,a.content,a.task_status,a.images,t1.name as follow_stage,t2.name as follow_way,a.plan_time,a.cancel_why')
        ->alias('a')
        ->join('ss_manystore m','a.follow_uid = m.id','left')
        ->join('ss_type t1','t1.id = a.follow_stage','left')
        ->join('ss_type t2','t2.id = a.follow_way','left')
        ->join('ss_user u','a.clew_id = u.id','left')
        ->join('ss_campus_clew_consultant c','u.course_consultant = c.id','left')
        ->where($where)
        ->select();

        foreach ($follow_record as & $value) {
            $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
            if($value['task_status'] == 0 && $value['plan_time'] > time())
            {
                $value['task_status'] = 2;
            }
            unset($value['plan_time']);
        }

        $this->success('获取数据成功','',$follow_record);
    }

    /**
     * 保存跟进记录
     *
     * @ApiTitle    获取跟进中信息列表

     * @ApiParams (name="id", type="integer", required=false, description="记录ID【为0时新增】")
     * @ApiParams (name="clew_id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="follow_stage", type="integer", required=false, description="跟进阶段")
     * @ApiParams (name="follow_way", type="integer", required=false, description="跟进方式")
     * @ApiParams (name="plan_time", type="date", required=false, description="计划时间")
     * @ApiParams (name="nextfollow_time", type="date", required=false, description="下次跟进时间")
     * @ApiParams (name="content", type="integer", required=false, description="跟进内容")
     * @ApiParams (name="nexttask_remark", type="integer", required=false, description="下次跟进任务备注")
     * @ApiParams (name="images", type="integer", required=false, description="图片【文件上传API接口返回参数url】")
     * @ApiParams (name="cancel_why", type="integer", required=false, description="取消原因")
     * @ApiParams (name="task_status", type="integer", required=false, description="任务状态【默认0】:0=计划,1=取消,2=完成")
     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657959411",
          "data": null
        })
     */
    public function saveFollowingRecord()
    {
        #允许传入的参数
        $auth_params = ['id','clew_id','follow_stage','follow_way','plan_time','nextfollow_time','content','nexttask_remark','images','cancel_why','task_status'];
        $param = $this->AuthParams($auth_params);

        if(!empty($param['id']))
        {
            $info = CampusFollowModel::get($param['id']);

            if(empty($info))
            {
                $this->error('跟进记录表不存在');
            }
        }
        else
        {
            $clew_id = !empty($param['clew_id']) ? intval($param['clew_id']) : 0;
            $userinfo = UserModel::get(intval($clew_id));

            if(empty($userinfo))
            {
                $this->error('线索不存在');
            }

            $info = new CampusFollowModel;
            $info->shop_id = $userinfo->shop_id;
            $info->clew_id = $userinfo->id;
            $info->follow_uid = $userinfo->follow_uid;
            $info->consult_course = $userinfo->consult_course;
            $info->collect_people = $userinfo->collect_people;
            $info->createtime = time();
        }

        $info->lastfollow_time = time();

        $param['task_status'] = empty($param['task_status']) ? 0 : intval($param['task_status']);

        if($param['task_status'] < 0 || $param['task_status'] > 2)
        {
            $this->error('请选择跟进状态');
        }

        if($param['task_status'] == 1)
        {
            if(empty($param['cancel_why']))
            {
                $this->error('请填写取消原因');
            }

            $info->task_status = 1;
            $info->cancel_why = $param['cancel_why'];
            $info->cancel_time = time();
            
        }
        else if($param['task_status'] == 2)
        {
            $info->task_status = 3;
            $info->complete_time = time();
            $info->updatetime = time();
        }
        else if($param['task_status'] == 0)
        {
            $info->updatetime = time();
        }

        if(!empty($param['task_status']) != 1)
        {
            if(!empty($param['follow_stage']))
            {
                $follow_stage_info = TypeModel::where(['type' => 'stage','id' => $param['follow_stage']])->find();
                if(empty($follow_stage_info))
                {
                    $this->error('请选择跟进阶段');
                }
                $info->follow_stage = $follow_stage_info['id'];
            }

            if(!empty($param['follow_way']))
            {
                $follow_way_info = TypeModel::where(['type' => 'way','id' => $param['follow_way']])->find();
                if(empty($follow_way_info))
                {
                    $this->error('请选择跟进方式'.$param['follow_way']);
                }
                $info->follow_way = $follow_way_info['id'];
            }
            
            //无更进时间时需添加
            if(empty($info->plan_time) || !empty($param['plan_time']))
            {
                $param['plan_time'] = strtotime($param['plan_time']);
                if(empty($param['plan_time']))
                {
                    $this->error('请选择计划跟进时间');
                }
                $info->plan_time = $param['plan_time'];
            }

            if(!empty($param['nextfollow_time']))
            {
                $param['nextfollow_time'] = strtotime($param['nextfollow_time']);
                if(empty($param['nextfollow_time']))
                {
                    $this->error('请选择下次跟进时间');
                }
                $info->nextfollow_time = $param['nextfollow_time'];
            }

            //无跟进内容时需添加
            if(empty($info->content) || !empty($param['content']))
            {
                $info->content = $param['content'];
            }

            if(!empty($param['nexttask_remark']))
            {
                $info->nexttask_remark = $param['nexttask_remark'];
            }

            if(!empty($param['images']) && !is_file('.'.$param['images']))
            {
                $this->error('请上传图片');
                $info->images = $param['images'];
            }
        }

        // 启动事务
        Db::startTrans();
        try
        {
            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('保存失败');
        }

        $this->success('保存成功','');
    }

    /**
     * 获取跟进中学员成长档案列表
     *
     * @ApiTitle    获取跟进中学员成长档案列表

     * @ApiParams (name="id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="type", type="integer", required=false, description="档案类型")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657964522",
          "data": [
            {
              "createtime": "2022-06-08 11:17:59",//记录时间
              "operation_user": "思明校区",//操作人
              "content": "测试评价",//评价
              "from": "teacher"//self来自自己，teacher来自老师
            },
            ......
          ]
        })
     */
    public function getGrowthPortfolioList()
    {
        $id = intval($this->request->param('id'));
        $type = intval($this->request->param('type'));

        $info = UserModel::field('a.id,a.truename')
        ->alias('a')
        ->where(['a.follow_uid' => $this->auth->id,'a.id' => $id])
        // ->fetchSql()
        ->find();

        if(empty($info))
        {
            $this->error('你不是该线索的跟进人');
        }

        $where = ['style' => 2];
        if($type > 0)
        {
            $where['type_id'] = $type;
        }

        $record = GrowthPortfolioModel::field('a.createtime,m.username as operation_user,a.content,a.e_id')
        ->alias('a')
        ->join('ss_manystore m','a.operation_id = m.id','left')
        ->join('ss_type t','t.id = a.type_id','left')
        ->where($where)
        ->where(function($query) use ($info){
            $query->whereOr('relation_id','like',"%,{$info['id']},%")
            ->whereOr('relation_id','like',"{$info['id']},%")
            ->whereOr('relation_id','like',"%,{$info['id']}")
            ->whereOr('relation_id',"{$info['id']}");
        })
        // ->fetchSql()
        ->select();

        foreach ($record as & $value) {
            $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

            $value['from'] = $value['e_id'] == 0 ? 'self' : 'teacher';
            unset($value['e_id']);
        }

        $this->success('获取数据成功','',$record);
    }

    /**
     * 建立跟进关系
     *
     * @ApiTitle    建立跟进关系

     * @ApiParams (name="clew_id", type="integer", required=false, description="学员ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "跟进该线索成功",
          "time": "1657995816",
          "data": null
        })
     */
    public function FollowUpClues()
    {
        #允许传入的参数
        $clew_id = intval($this->request->param('clew_id'));

        $info = UserModel::get($clew_id);

        if(empty($info))
        {
            $this->error('线索不存在');
        }

        if(!empty($info->follow_uid))
        {
            $this->error('该线索已有跟进人');
        }

        if($info->shop_id != $this->auth_id && $info->is_publicpool == 0)
        {
            $this->error('该线索非本校区');
        }

        // 启动事务
        Db::startTrans();
        try
        {
            $info->follow_uid = $this->auth->id;
            $info->shop_id = $this->auth->shop_id;
            $info->follow_status = 3;
            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('跟进该线索失败');
        }

        $this->success('跟进该线索成功','');
    }


}
